<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\BotSetting as SettingM;
use plugin\wechat\app\service\BotSetting as SettingService;
use plugin\wechat\app\TenantController;
use Support\Request;

class Botsetting extends TenantController
{
    /**
     * @var SettingM
     */
    protected $model;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new SettingM();
    }

    private function tabList(){
        return [
            'default' => [
                'title' => '默认设置',
                'href' => url('index', ['name' => 'default'])
            ],
            'save' => [
                'title' => '安全设置',
                'href' => url('index', ['name' => 'save'])
            ],
        ];
    }


    public function index(Request $request){
        $current_name = input('name', 'default');
        $setting = $this->model->where([
            $this->tenantWhere(),
            ['name' ,'=', $current_name]
        ])->find();

        if($request->isPost()){
            $post_data = input('post.');
            unset($post_data['__token__']);
            $company_id = TenantService::getCompanyId();
            if(empty($setting)){
                $res = $this->model->createOne([
                    'company_id' => $company_id,
                    'name' => $current_name,
                    'title' => $this->tabList()[$current_name]['title'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE)
                ]);
            }else{
                $res = $this->model->update([
                    'id' => $setting['id'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE)
                ]);
            }
            if($res){
                SettingService::getSettings($company_id, $current_name, true);
                return $this->success('保存成功!', url('index', ['name' => $current_name]));
            }
            return $this->error('保存失败!', '', ['token' => token()]);
        }

        if(empty($setting)){
            $data = [];
        }else{
            $data = json_decode($setting['value'], true);
        }
        $builder = new FormBuilder();
        switch ($current_name){
            case 'save':
                $builder->addFormItem('step_time', 'text', '群发间隔时间', '格式：1-4，单位秒');
                break;
            case 'default':
                $builder->addFormItem('app_key', 'text', 'AppKey', '默认机器人框架的appkey')
                    ->addFormItem('url', 'text', '接口地址', '默认机器人框架的接口地址');
                break;
        }
        $builder->setFormData($data)
            ->setTabNav($this->tabList(), $current_name);
        return $builder->show();
    }
}